package com.zs.games.utils;

import com.zs.games.resultTool.ResultCodeEnum;
import com.zs.games.exception.APIException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;

/**
 * 
 * @date 2023年05月10日 14:55
 */
@Slf4j
public class DownFileUtil {
    /**
     *
     * 导出txt文件
     * @Author: Gjm
     */
    public static void exportTxt(HttpServletResponse response, String text,String fileName){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain;charset=utf-8");
        response.addHeader( "Content-Disposition", "attachment; filename= " + fileName +".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outputStream = null ;
        try {
            outputStream = response.getOutputStream();
            buff = new BufferedOutputStream(outputStream);
            buff.write(text.getBytes("utf-8"));
            buff.flush();
            buff.close();
        } catch (Exception e){
            log.error("导出文件出现异常！", e);
            throw new APIException(ResultCodeEnum.DOWNLOAD_ERROR);
        }finally {
            try {
                buff.close();
                outputStream.close();
            }catch (Exception e){
                log.error("关闭输出流出现异常！", e);
            }


        }



    }
}
